package adapletplugin.commands;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import objects.MappingFile;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import adapletplugin.Activator;

public class Save extends AbstractHandler
{

	@Override
	public boolean isEnabled()
	{
		return Activator.getDefault().getCurrentProject() != null;
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

		FileDialog dialog = new FileDialog(shell, SWT.SAVE);

		MappingFile mapFile = Activator.getDefault().getCurrentProject();

		dialog.setFilterExtensions(new String[] { "*.ser" });
		dialog.setFileName(mapFile.getMapFileName());

		dialog.setOverwrite(true);

		dialog.open();

		String outFileName = dialog.getFileName();
		String outFilePath = dialog.getFilterPath();

		if (outFileName == null || outFilePath == null)
		{
			return null;
		}

		FileOutputStream outFStream = null;
		ObjectOutputStream outOStream = null;

		try
		{
			outFStream = new FileOutputStream(new File(outFilePath, outFileName));
			outOStream = new ObjectOutputStream(outFStream);

			outOStream.writeObject(mapFile);

			outOStream.close();
			outOStream = null;

			outFStream.close();
			outFStream = null;
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}
